<template>
  <div class="app-container" 
       :class="[currentTheme, {'night-mode': isNightMode}]"
       :style="{ backgroundColor: backgroundColor }">
    <div class="read-container">
      <!-- 顶部导航栏 -->
      <div class="read-header">
        <div class="header-left">
          <el-button icon="el-icon-back" @click="goBack" plain>返回</el-button>
          <span class="novel-title">{{ novelName }}</span>
        </div>
        <div class="header-right">
          <el-button 
            class="bookshelf-btn" 
            :class="{ 'in-bookshelf': inBookshelf }"
            @click="handleAddToBookshelf"
            :icon="inBookshelf ? 'el-icon-reading' : 'el-icon-plus'"
            plain
          >
            {{ inBookshelf ? '已在书架' : '加入书架' }}
          </el-button>
          <el-button type="text" @click="showSettings = !showSettings" plain>设置</el-button>
        </div>
      </div>
      
      <!-- 阅读设置面板 -->
      <div class="settings-panel" v-if="showSettings">
        <div class="settings-header">
          <span>阅读设置</span>
          <el-button type="text" icon="el-icon-close" @click="showSettings = false"></el-button>
        </div>
        <div class="settings-content">
          <div class="settings-item">
            <span>字体大小</span>
            <el-slider v-model="fontSize" :min="14" :max="24" :step="1" @change="handleFontSizeChange"></el-slider>
          </div>
          <div class="settings-item">
            <span>背景颜色</span>
            <div class="theme-buttons">
              <el-button 
                v-for="(name, theme) in themeNames" 
                :key="theme"
                :class="['theme-button', { active: currentTheme === theme }]"
                @click="switchTheme(theme)">
                {{ name }}
              </el-button>
            </div>
          </div>
          <div class="settings-item">
            <span>夜间模式</span>
            <el-switch v-model="isNightMode" @change="handleNightModeChange"></el-switch>
          </div>
        </div>
      </div>
      
      <!-- 章节信息 -->
      <div class="chapter-info">
        <h2 class="chapter-title">{{ chapterInfo.chapterTitle }}</h2>
        <div class="chapter-meta">
          <span class="meta-item">
            <i class="el-icon-document"></i>
            {{ chapterInfo.orderNum }}
          </span>
          <span class="meta-item" v-if="chapterInfo.author">
            <i class="el-icon-user"></i>
            {{ chapterInfo.author }}
          </span>
          <span class="meta-item" v-if="chapterInfo.wordCount">
            <i class="el-icon-notebook-2"></i>
            {{ chapterInfo.wordCount }}字
          </span>
          <span class="meta-item" v-if="chapterInfo.createTime">
            <i class="el-icon-time"></i>
            {{ formatDate(chapterInfo.createTime) }}
          </span>
          <span class="meta-item" :class="{'vip': chapterInfo.subscribe === 1}">
            <i :class="chapterInfo.subscribe === 1 ? 'el-icon-lock' : 'el-icon-unlock'"></i>
            {{ chapterInfo.subscribe === 1 ? 'VIP章节' : '免费章节' }}
          </span>
        </div>
      </div>
      
      <!-- 章节内容 -->
      <div class="chapter-content" 
           :style="{ fontSize: fontSize + 'px', lineHeight: lineHeight }" 
           ref="contentRef">
        <p v-for="(paragraph, index) in formattedContent" :key="index">{{ paragraph }}</p>
      </div>
      
      <!-- 阅读进度条 -->
      <div class="progress-bar">
        <div class="progress" :style="{ width: readingProgress + '%' }"></div>
      </div>
      
      <!-- 底部导航 -->
      <div class="chapter-nav">
        <el-button type="primary" @click="prevChapter" :disabled="!hasPrev">上一章</el-button>
        <el-button type="primary" @click="toggleAutoScroll" v-if="autoScroll">
          {{ isScrolling ? '暂停' : '继续' }}
        </el-button>
        <el-button type="primary" @click="nextChapter" :disabled="!hasNext">下一章</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getChapterContent, getNextChapter, getPreChapter } from "@/api/bookshelf/bookshelf";
import { addBookShelf, isInBookShelf } from "@/api/bookshelf/bookshelf";
import store from "@/store";

export default {
  name: "NovelRead",
  data() {
    return {
      novelName: "",
      chapterInfo: {
        orderNum: "",
        chapterTitle: "",
        author: "",
        content: "",
        wordCount: "",
        subscribe: 0,
        createTime: ""
      },
      hasPrev: false,
      hasNext: false,
      // 阅读设置
      fontSize: 18,
      lineHeight: 1.8,
      themeNames: {
        'theme-default': '默认',
        'theme-blue': '淡蓝',
        'theme-green': '淡绿',
        'theme-pink': '淡粉',
        'theme-yellow': '淡黄'
      },
      currentTheme: 'theme-default',
      isNightMode: false,
      showSettings: false,
      // 自动滚动
      autoScroll: false,
      isScrolling: false,
      scrollSpeed: 5,
      scrollInterval: null,
      // 阅读进度
      readingProgress: 0,
      isFromWriter: false,
      userId: store.state.user.id,
      inBookshelf: false
    };
  },
  created() {
    console.log('组件创建，路由参数:', this.$route.query);
    // 判断是否从作家页面跳转
    this.isFromWriter = this.$route.query.from === 'writer';
    this.initChapter();
    // 从本地存储加载阅读设置
    this.loadSettings();
    // 检查是否在书架中
    this.checkBookshelfStatus();
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    this.stopAutoScroll();
  },
  watch: {
    '$route.query': {
      handler(newQuery) {
        console.log('路由参数变化:', newQuery);
        this.initChapter();
      },
      immediate: true,
      deep: true
    },
    // 监听设置变化，保存到本地存储
    fontSize() {
      this.saveSettings();
    },
    lineHeight() {
      this.saveSettings();
    },
    currentTheme() {
      this.saveSettings();
    },
    isNightMode() {
      this.saveSettings();
    },
    // 监听自动滚动开关
    autoScroll(newVal) {
      if (newVal) {
        this.startAutoScroll();
      } else {
        this.stopAutoScroll();
      }
    }
  },
  methods: {
    initChapter() {
      console.log('初始化章节，当前路由参数:', this.$route.query);
      this.novelName = this.$route.query.title;
      const orderNum = this.$route.query.orderNum;
      
      // 如果是从其他页面点击过来的，不显示参数无效的错误
      if (!this.novelName || !orderNum) {
        console.log('参数不完整，可能是从其他页面点击过来的');
        // 不显示错误消息，静默处理
        return;
      }
      
      console.log('开始获取章节内容:', { title: this.novelName, orderNum });
      this.getChapterContent();
    },
    getChapterContent() {
      console.log('调用getChapterContent方法:', { title: this.novelName, orderNum: this.$route.query.orderNum });
      getChapterContent(this.novelName, this.$route.query.orderNum, this.userId)
        .then(response => {
          console.log('获取章节内容成功:', response);
          if (response.code === 200) {
            if (typeof response.data === 'string') {
              // 处理未订阅的情况
              this.$message.warning(response.data);
              this.chapterInfo = {
                orderNum: this.$route.query.orderNum,
                chapterTitle: "未订阅章节",
                content: "请订阅后查看完整内容",
                subscribe: 1
              };
            } else {
              this.chapterInfo = response.data;
            }
            // 检查是否有上一章和下一章
            this.checkChapterNavigation();
          }
        })
        .catch(error => {
          console.error('获取章节内容失败:', error);
          this.$message.error("获取章节内容失败");
        });
    },
    // 检查章节导航状态
    checkChapterNavigation() {
      // 检查是否有上一章
      getPreChapter(this.novelName, this.chapterInfo.orderNum, this.userId)
        .then(response => {
          this.hasPrev = response.code === 200;
        })
        .catch(() => {
          this.hasPrev = false;
        });
      
      // 检查是否有下一章
      getNextChapter(this.novelName, this.chapterInfo.orderNum, this.userId)
        .then(response => {
          this.hasNext = response.code === 200;
        })
        .catch(() => {
          this.hasNext = false;
        });
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString();
    },
    nextChapter() {
      getNextChapter(this.novelName, this.chapterInfo.orderNum, this.userId)
        .then(response => {
          if (response.code === 200) {
            // 跳转到下一章
            this.$router.push({
              path: '/novel/read',
              query: {
                title: this.novelName,
                orderNum: response.data.orderNum
              }
            });
          } else {
            this.$message.info(response.msg || "已经是最后一章了");
          }
        })
        .catch(error => {
          console.error('获取下一章失败:', error);
          this.$message.error("获取下一章失败");
        });
    },
    prevChapter() {
      getPreChapter(this.novelName, this.chapterInfo.orderNum, this.userId)
        .then(response => {
          if (response.code === 200) {
            // 跳转到上一章
            this.$router.push({
              path: '/novel/read',
              query: {
                title: this.novelName,
                orderNum: response.data.orderNum
              }
            });
          }
        })
        .catch(error => {
          console.error('获取上一章失败:', error);
          this.$message.error("获取上一章失败");
        });
    },
    // 返回上一页
    goBack() {
      this.$router.replace({
        path: '/novel/detail',
        query: {
          title: this.novelName
        }
      });
    },
    // 加载阅读设置
    loadSettings() {
      const settings = localStorage.getItem('novelReadSettings');
      if (settings) {
        const { fontSize, currentTheme, isNightMode } = JSON.parse(settings);
        this.fontSize = fontSize || 18;
        this.currentTheme = currentTheme || 'theme-default';
        this.isNightMode = isNightMode || false;
      }
    },
    // 保存阅读设置
    saveSettings() {
      const settings = {
        fontSize: this.fontSize,
        currentTheme: this.currentTheme,
        isNightMode: this.isNightMode
      };
      localStorage.setItem('novelReadSettings', JSON.stringify(settings));
    },
    // 开始自动滚动
    startAutoScroll() {
      this.stopAutoScroll(); // 先清除可能存在的定时器
      this.isScrolling = true;
      
      // 计算滚动速度（毫秒）
      const scrollInterval = 1000 / this.scrollSpeed;
      
      this.scrollInterval = setInterval(() => {
        const content = this.$refs.contentRef;
        if (content) {
          // 计算阅读进度
          const scrollTop = content.scrollTop;
          const scrollHeight = content.scrollHeight;
          const clientHeight = content.clientHeight;
          this.readingProgress = (scrollTop / (scrollHeight - clientHeight)) * 100;
          
          // 如果已经滚动到底部，停止滚动
          if (scrollTop + clientHeight >= scrollHeight) {
            this.stopAutoScroll();
            return;
          }
          
          // 滚动一行
          content.scrollTop += 1;
        }
      }, scrollInterval);
    },
    // 停止自动滚动
    stopAutoScroll() {
      if (this.scrollInterval) {
        clearInterval(this.scrollInterval);
        this.scrollInterval = null;
      }
      this.isScrolling = false;
    },
    // 切换自动滚动状态
    toggleAutoScroll() {
      if (this.isScrolling) {
        this.stopAutoScroll();
      } else {
        this.startAutoScroll();
      }
    },
    // 处理字体大小变化
    handleFontSizeChange(size) {
      this.fontSize = size;
      this.saveSettings();
    },
    // 处理背景颜色变化
    switchTheme(theme) {
      this.currentTheme = theme;
      this.saveSettings();
    },
    // 处理夜间模式变化
    handleNightModeChange(isNight) {
      this.isNightMode = isNight;
      this.saveSettings();
    },
    handleEdit() {
      this.$router.push({
        path: '/writer/novelDetail',
        query: {
          title: this.novelName
        }
      });
    },
    /** 处理加入书架 */
    handleAddToBookshelf() {
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      if (this.inBookshelf) {
        this.$message.info('该小说已在书架中');
        return;
      }
      
      addBookShelf(this.userId, this.novelName).then(response => {
        if (response.code === 200) {
          this.inBookshelf = true;
          this.$message.success('已加入书架');
        } else {
          this.$message.error(response.msg || '加入书架失败');
        }
      }).catch(error => {
        console.error('加入书架失败:', error);
        this.$message.error('加入书架失败');
      });
    },
    /** 检查是否在书架中 */
    checkBookshelfStatus() {
      if (!this.userId || !this.novelName) return;
      
      isInBookShelf(this.userId, this.novelName).then(response => {
        if (response.code === 200) {
          this.inBookshelf = response.data === 1;
        }
      }).catch(error => {
        console.error('检查书架状态失败:', error);
      });
    }
  },
  computed: {
    formattedContent() {
      if (!this.chapterInfo.content) return [];
      return this.chapterInfo.content.split('\n').filter(p => p.trim());
    },
    textColor() {
      if (this.isNightMode) return '#e0e0e0';
      // 根据背景色的亮度自动调整文字颜色
      const color = this.backgroundColor.replace('#', '');
      const r = parseInt(color.substr(0, 2), 16);
      const g = parseInt(color.substr(2, 2), 16);
      const b = parseInt(color.substr(4, 2), 16);
      const brightness = (r * 299 + g * 587 + b * 114) / 1000;
      return brightness > 128 ? '#333333' : '#ffffff';
    },
    metaTextColor() {
      if (this.isNightMode) return '#999999';
      const color = this.backgroundColor.replace('#', '');
      const r = parseInt(color.substr(0, 2), 16);
      const g = parseInt(color.substr(2, 2), 16);
      const b = parseInt(color.substr(4, 2), 16);
      const brightness = (r * 299 + g * 587 + b * 114) / 1000;
      return brightness > 128 ? '#666666' : '#cccccc';
    },
    pageBackgroundColor() {
      return this.themeNames[this.currentTheme]?.page || '#f5f5f5';
    },
    contentBackgroundColor() {
      return this.isNightMode ? '#2d2d2d' : (this.themeNames[this.currentTheme]?.content || '#ffffff');
    },
    backgroundColor() {
      return this.themeNames[this.currentTheme] || '#f5f5f5';
    }
  }
};
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  padding: 20px 0;
  transition: all 0.3s ease;
}

/* 主题颜色 */
.theme-default {
  background-color: v-bind(pageBackgroundColor);
}

.theme-blue {
  background-color: v-bind(pageBackgroundColor);
}

.theme-green {
  background-color: v-bind(pageBackgroundColor);
}

.theme-pink {
  background-color: v-bind(pageBackgroundColor);
}

.theme-yellow {
  background-color: v-bind(pageBackgroundColor);
}

.read-container {
  width: 75%;
  margin: 0 auto;
  padding: 20px;
  background-color: v-bind(contentBackgroundColor);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  min-height: 90vh;
  transition: all 0.3s ease;
}

.night-mode {
  background-color: #1a1a1a !important;
}

.night-mode .read-container {
  background-color: #2d2d2d;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.read-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.night-mode .read-header {
  border-bottom-color: #444;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.novel-title {
  font-size: 18px;
  font-weight: 500;
  color: v-bind(textColor);
}

.night-mode .novel-title {
  color: v-bind(textColor);
}

.settings-panel {
  position: fixed;
  left: 50%;
  top: 80px;
  transform: translateX(-50%);
  width: 320px;
  max-height: calc(100vh - 160px);
  overflow-y: auto;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  background: inherit;
  z-index: 1;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.settings-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.settings-item span {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.night-mode .settings-panel {
  background-color: rgba(61, 61, 61, 0.95);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

.night-mode .settings-item span {
  color: #999;
}

.chapter-info {
  margin-bottom: 30px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.night-mode .chapter-info {
  background-color: rgba(45, 45, 45, 0.5);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.chapter-title {
  font-size: 24px;
  font-weight: bold;
  color: v-bind(textColor);
  margin-bottom: 15px;
  text-align: center;
  transition: all 0.3s ease;
}

.night-mode .chapter-title {
  color: v-bind(textColor);
}

.chapter-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: center;
  color: v-bind(metaTextColor);
  font-size: 14px;
  transition: all 0.3s ease;
}

.night-mode .chapter-meta {
  color: v-bind(metaTextColor);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 4px 8px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.night-mode .meta-item {
  background: #3d3d3d;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.meta-item.vip {
  color: #e6a23c;
  background: #fdf6ec;
}

.night-mode .meta-item.vip {
  background: #3d3d3d;
  color: #e6a23c;
}

.meta-item i {
  font-size: 16px;
}

.chapter-content {
  line-height: 1.8;
  color: v-bind(textColor);
  margin-bottom: 30px;
  text-align: justify;
  padding: 0 10px;
  transition: all 0.3s ease;
}

.chapter-content p {
  margin-bottom: 1em;
  text-indent: 2em;
}

.chapter-content p:last-child {
  margin-bottom: 0;
}

.night-mode .chapter-content {
  color: v-bind(textColor);
}

.progress-bar {
  height: 4px;
  background: #eee;
  border-radius: 2px;
  margin-bottom: 20px;
  overflow: hidden;
}

.night-mode .progress-bar {
  background: #444;
}

.progress {
  height: 100%;
  background: #409EFF;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.chapter-nav {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.night-mode .chapter-nav {
  border-top-color: #444;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .read-container {
    width: 85%;
  }
  .settings-panel {
    left: 10px;
    width: 260px;
  }
}

@media (max-width: 768px) {
  .read-container {
    width: 95%;
    padding: 15px;
  }
  
  .chapter-content {
    padding: 0 5px;
  }
  
  .chapter-nav {
    flex-direction: column;
    gap: 10px;
  }
  
  .chapter-nav .el-button {
    width: 100%;
  }
  
  .settings-panel {
    position: fixed;
    left: 0;
    right: 0;
    top: auto;
    bottom: 0;
    transform: none;
    width: 100%;
    max-height: 80vh;
    border-radius: 16px 16px 0 0;
    padding: 20px;
    margin: 0;
  }
  
  .settings-header {
    margin-bottom: 15px;
  }
  
  .settings-content {
    gap: 15px;
    padding-bottom: env(safe-area-inset-bottom);
  }
}

.theme-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.theme-button {
  min-width: 80px;
  height: 32px;
  margin: 5px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 15px;
}

.theme-button.active {
  color: #409EFF;
  border-color: #409EFF;
  background-color: #ecf5ff;
}

.bookshelf-btn {
  margin-right: 10px;
  transition: all 0.3s ease;
}

.bookshelf-btn.in-bookshelf {
  color: #67c23a;
  border-color: #67c23a;
}

.bookshelf-btn.in-bookshelf:hover {
  color: #85ce61;
  border-color: #85ce61;
}

.bookshelf-btn i {
  margin-right: 5px;
}
</style> 